<?php

namespace App\Models;

use App\Models\ComModel;

class EmailModel extends ComModel
{

    public $tablename;

    public function __construct()
    {
        parent::__construct();
        $this->tablename = 'email';
    }

    //验证
    private function _validate($data, $id = 0)
    {
        $data = esc($data);

        if (!isset($data) || empty($data)) {
            return ams_rt(1, '请填写邮箱');
        } elseif (!isset($data['email']) || !$data['email']) {
            return ams_rt(1, '请填写收件箱');
        } elseif (!isset($data['content']) || !$data['content']) {
            return ams_rt(1, '请填写内容');
        }

        if (isset($data['thumb']) && $data['thumb']) {
            $row = $this->db->table('attachment')->select('related')->where('id', intval($data['thumb']))->get()->getRowArray();
            if ($row['related'] && !$id) {
                return ams_rt(1, '图片来源不正常');
            }
        }
        return ams_rt(0, 'ok', $data);
    }

    private function _where(&$select, $data)
    {
        if ($data) {
            if (isset($data['email']) && $data['email']) {
                $select->where('email', $data['email']);
            }

            //状态
            if (isset($data['status']) && ($data['status'] || $data['status'] == '0')) {
                $select->where('status', (int) $data['status']);
            }

        }
        return $data;
    }

    public function limit_page($page = 0, $size = 10, $total = 0, $param = [])
    {
        $page = max(1, (int) $page);
        $total = (int) $total;
        unset($param['page']);
        if ($param) {
            $param = esc($param);
        }
        if ($size > 0 && !$total) {
            $select = $this->db->table($this->tablename)->select('count(*) as total');
            $param = $this->_where($select, $param);
            $query = $select->get();

            if (!$query) {
                log_message('error', '数据查询失败：' . $this->tablename);
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->tablename);
        $param = $this->_where($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy('id', 'desc')->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->tablename);
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['inputtime_date'] = date('Y-m-d H:i:s', $v['inputtime']);
                $data[$k]['updatetime_date'] = $v['updatetime'] ? date('Y-m-d H:i:s', $v['updatetime']) : '';
            }
        }
        $param['total'] = $total;
        return [$data, $total, $param];
    }

    public function add($data)
    {
        $rt = $this->_validate($data);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];

        $idata = array(
            'title' => $data['title'],
            'description' => isset($data['description']) ? $data['description'] : '',
            'thumb' => $data['thumb'] ? $data['thumb'] : '',
            'phone' => isset($data['phone']) ? $data['phone'] : '',
            'displayorder' => 0,
            'updatetime' => time(),
            'inputtime' => time(),
            'status' => (isset($data['status']) && $data['status']) ? 1 : 0,
        );
        $this->db->table($this->tablename)->insert($idata);
        $id = $this->db->insertID();
        if ($id) {
            if ($data['thumb']) {
                $related = $this->tablename . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
            }
            return ams_rt(0, 'ok', $id);
        }
        return ams_rt(1, '操作失败');
    }

    public function send($data = [])
    {

        $rt = $this->_validate($data);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];

        $cfg = $this->getSetting();
        if (!$cfg['EMAIL_HOST']) {
            $this->_json(1, '您还没有设置邮件服务器');
        }

        $config['protocol'] = 'sendmail';
        $config['charset'] = 'iso-8859-1';
        $config['wordWrap'] = true;
        $config['SMTPCrypto'] = 'ssl';
        $config['SMTPHost'] = $cfg['EMAIL_HOST'];
        $config['SMTPPort'] = $cfg['EMAIL_PORT'];
        $config['SMTPPass'] = $cfg['EMAIL_PASS'];
        $config['SMTPUser'] = $cfg['EMAIL_USER'];
        $config['mailType'] = 'text'; //内容格式:text or html

        $email = \Config\Services::email();
        $email->initialize($config);

        $email->setFrom($cfg['EMAIL_USER'], $cfg['EMAIL_USERNAME']);
        $email->setTo($data['email']);
        $email->setSubject('CI4 Email Test');
        $email->setMessage('CI4 Testing the email class.');
        if ($email->send()) {
            $status = 1;
        } else {
            $errmsg = $email->printDebugger();
            $status = 0;
        }

        $idata = array(
            'email' => isset($data['email']) ? $data['email'] : '',
            'content' => isset($data['content']) ? $data['content'] : '',
            'type' => 1,
            'inputtime' => time(),
            'status' => $status,
            'name' => (isset($data['name']) && $data['name']) ? $data['name'] : $data['email'],
            'thumb' => $data['thumb'] ? $data['thumb'] : '',
            'errmsg' => isset($errmsg) ? $errmsg : '',
            'updatetime' => time(),

        );
        $this->db->table($this->tablename)->insert($idata);
        $id = $this->db->insertID();
        if ($id) {
            if ($data['thumb']) {
                $related = $this->tablename . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
            }
            return ams_rt(0, 'ok', $id);
        }
        return ams_rt(1, '操作失败');

    }

    public function getinfo($id)
    {
        $id = intval($id);
        $data = $this->db->table($this->tablename)->where('id', $id)->limit(1)->get()->getRowArray();
        if ($data['thumb']) {
            $att = $this->db->table('attachment')->where('id', intval($data['thumb']))->get()->getRowArray();
            // $att['attachment'] = '/writable/'.$att['attachment'];
            $data['thumb_info'] = $att;
        }
        return ams_rt(0, 'ok', $data);
    }

    /**
     * 修改信息 $edit 新数据
     */
    public function edit($id, $data)
    {
        $rt = $this->_validate($data, $id);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];

        $idata = array(
            'title' => $data['title'],
            'description' => isset($data['description']) ? $data['description'] : '',
            'thumb' => $data['thumb'] ? $data['thumb'] : '',
            'phone' => isset($data['phone']) ? $data['phone'] : '',
            'updatetime' => time(),
            'status' => (isset($data['status']) && $data['status']) ? 1 : 0,
        );
        $this->db->table($this->tablename)->where('id', $id)->update($idata);
        if ($id) {
            if ($data['thumb']) {
                $related = $this->tablename . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
            }
            return ams_rt(0, 'ok', $id);
        }
        return ams_rt(1, '操作失败');
    }

    public function del($id = 0)
    {
        if (!$id) {
            return ams_rt(1, '操作失败:参数错误');
        }
        $row = $this->db->table($this->tablename)->where('id', intval($id))->get()->getRowArray();
        if ($row) {
            if ($row['thumb']) {
                $this->db->table('attachment')->where('id', intval($row['thumb']))->delete();
            }
            $this->db->table($this->tablename)->where('id', intval($id))->delete();
        }
        return ams_rt(0, 'ok', $row);
    }

    /**
     * 条件查询
     */
    private function _where_config(&$select, $data)
    {
        if ($data) {

            if (isset($data['type']) && $data['type']) {
                $select->where('type', $data['type']);
            }

            if (isset($data['code']) && $data['code']) {
                $select->where('code', $data['code']);
            }

            if (isset($data['name']) && $data['name']) {
                $select->like('name', $data['name'], 'both');
            }

            if (isset($data['status']) && ($data['status'] == 1 || $data['status'] == '0')) {
                $select->where('status', $data['status']);
            }

            // 时间搜索
            if (isset($data['start']) && $data['start']) {
                $data['end'] = strtotime(date('Y-m-d 23:59:59', $data['end'] ? $data['end'] : time()));
                $data['start'] = strtotime(date('Y-m-d 00:00:00', $data['start']));
                $select->where('addtime BETWEEN ' . $data['start'] . ' AND ' . $data['end']);
            } elseif (isset($data['end']) && $data['end']) {
                $data['end'] = strtotime(date('Y-m-d 23:59:59', $data['end']));
                $data['start'] = 1;
                $select->where('addtime BETWEEN ' . $data['start'] . ' AND ' . $data['end']);
            }
        }
        return $data;
    }

    /**
     * 数据分页显示
     */
    public function limit_page_config($page = 0, $size = 10, $total = 0, $param = [])
    {
        ams_clean_xss($param);

        $page = max(1, (int) $page);
        $total = (int) $total;
        unset($param['page']);
        if ($size > 0 && !$total) {
            $select = $this->db->table($this->tablename . '_config')->select('count(*) as total');
            $param = $this->_where_config($select, $param);
            $query = $select->get();
            if (!$query) {
                log_message('error', '数据查询失败：' . $this->tablename . '_config');
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->tablename . '_config');
        $param = $this->_where_config($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy('id', 'asc')->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->tablename . '_config');
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['addtime_date'] = date('Y-m-d H:i:s', $v['addtime']);
            }
        }
        $param['total'] = $total;
        return [$data, $total, $param];
    }

    //新增和编辑全部数据时验证
    private function _validate_config($data, $id = 0)
    {
        if (!$data) {
            return ams_rt(1, '参数错误');
        }
        $data = esc($data);

        if (!$data['name']) {
            return ams_rt(1, '名称必须填写');
        } elseif (!$data['code']) {
            return ams_rt(1,'标识必须填写');
        } elseif (!$data['keyvalue']) {
            return ams_rt(1, '参数必须填写');
        }

        $flag = $this->field_exitsts($this->tablename . '_config', 'name', $data['name'], $id);
        if ($flag) {
            return ams_rt(1, '名称已存在');
        }

        $flag = $this->field_exitsts($this->tablename . '_config', 'code', $data['code'], $id);
        if ($flag) {
            return ams_rt(1, '标识已存在');
        }

        return ams_rt(0, 'ok', $data);
    }

    //
    public function getCats()
    {
        $rows = $this->db->table($this->tablename . '_config')->select('id,code,name')->get()->getResultArray();
        if (!$rows) {
            $rows = [];
        }
        return $rows;
    }

    //添加支付平台
    public function addConfig($data)
    {
        $odata = $data;
        $rt = $this->_validate_config($data);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];
        $data['keyvalue'] = json_encode($data['keyvalue']);
        $data['addtime'] = time();
        $this->db->table($this->tablename . '_config')->insert($data);
        $id = $this->db->insertID();
        if ($id) {
            unset($odata);
            if (isset($data['thumb']) && $data['thumb']) {
                $related = $this->tablename . '_config' . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
            }
            $data['id'] = $id;
            $data['keyvalue'] = json_decode($data['keyvalue'], true);
            return ams_rt(0, '操作成功', $data);
        }
        return ams_rt(1, '操作失败', $odata);
    }

    //修改支付平台
    public function editConfig($id, $data)
    {
        $odata = $data;
        $id = intval($id);
        $row = $this->db->table($this->tablename . '_config')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在');
        }
        $rt = $this->_validate_config($data, $id);
        if ($rt['code']) {
            return $rt;
        }

        $data = $rt['data'];
        $data['addtime'] = time();
        $data['keyvalue'] = json_encode($data['keyvalue']);
        $flag = $this->db->table($this->tablename . '_config')->where('id', $id)->update($data);

        if (isset($data['thumb']) && $data['thumb']) {
            $related = $this->tablename . '_config' . '-' . $id;
            $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
        }

        return ams_rt(0, '操作成功', $odata);
    }

    //删除支付平台
    public function delConfig($id)
    {
        if (!$id) {
            return ams_rt(1, '参数错误');
        }
        $row = $this->db->table($this->tablename . '_config')->select('id,name,code')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在', []);
        }
        $this->db->table($this->tablename . '_config')->where('id', $id)->delete();
        return ams_rt(0, '操作成功', $row);
    }

    public function switchStatus($id)
    {
        $id = intval($id);
        if (!$id) {
            return ams_rt(1, '参数错误');
        }

        $row = $this->db->table($this->tablename . '_config')->select('id,name,code,status')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在');
        }
        if ($row['status'] == 1) {
            $status = 0;
        } else {
            $status = 1;
        }
        $this->db->table($this->tablename . '_config')->where('id', $id)->update(['status' => $status]);
        return ams_rt(0, '操作成功', $row);
    }

    public function setdisplayorder($id, $displayorder)
    {
        return $this->displayorder($this->tablename, $id, $displayorder);
    }

    //获取
    public function getInfoId($id)
    {
        $id = intval($id);
        $row = $this->db->table($this->tablename . '_config')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return null;
        }
        if ($row['thumb']) {
            $att = $this->db->table('attachment')->where('id', intval($row['thumb']))->get()->getRowArray();
            $row['thumb_info'] = $att;
        }
        $row['addtime_date'] = date('Y-m-d H:i', $row['addtime']);
        $row['keyvalue'] = json_decode($row['keyvalue'], true);
        if ($row['keyvalue'] && is_array($row['keyvalue'])) {
            foreach ($row['keyvalue'] as $v) {
                $row['config'][$v['key']] = $v['value'];
            }
        }
        return $row;
    }

    public function getInfoCode($code)
    {
        ams_clean_xss($code);
        $row = $this->db->table($this->tablename . '_config')->where('code', $code)->get()->getRowArray();
        if (!$row) {
            return null;
        }
        if ($row['thumb']) {
            $att = $this->db->table('attachment')->where('id', intval($row['thumb']))->get()->getRowArray();
            $row['thumb_info'] = $att;
        }
        $row['addtime_date'] = date('Y-m-d H:i', $row['addtime']);
        $row['keyvalue'] = json_decode($row['keyvalue'], true);
        if ($row['keyvalue'] && is_array($row['keyvalue'])) {
            foreach ($row['keyvalue'] as $v) {
                $row['config'][$v['key']] = $v['value'];
            }
        }
        return $row;
    }

}
